﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("YUIAspNet");

YUIAspNet.DataTable = function(element) {
    YUIAspNet.DataTable.initializeBase(this, [element]);
}

YUIAspNet.DataTable.prototype = {
    initialize: function() {
        YUIAspNet.DataTable.callBaseMethod(this, 'initialize');
    },

    initializeYUIControl: function(sender, args) {

        this._yuiControl = null;

        var columns = this._parseColumns();

        var src = this.get_DataSource();
        if (!src.responseSchema.metaFields) src.responseSchema.metaFields = {};
        src.responseSchema.metaFields.totalRecords = "totalRecords";

        var config = this._buildConfig();
              
        if (this.get_Width() || this.get_Height()) {
            this._yuiControl = new YAHOO.widget.ScrollingDataTable(this.get_Container(), columns, src, config);
        }
        else
            this._yuiControl = new YAHOO.widget.DataTable(this.get_Container(), columns, src, config);

        // ritl.de
        // Subscribe to events for row selection
        if(this.get_EnableRowSelection())
            this._yuiControl.subscribe("rowClickEvent", this._yuiControl.onEventSelectRow);
  
        if(this.get_EnableRowHover()) {      
            this._yuiControl.subscribe("rowMouseoverEvent", this._yuiControl.onEventHighlightRow);
            this._yuiControl.subscribe("rowMouseoutEvent", this._yuiControl.onEventUnhighlightRow);
        }
        
        this._yuiControl.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
            oPayload.totalRecords = oResponse.meta.totalRecords;
            return oPayload;
        };
    },

    _buildConfig: function() {
//        var selection = "standard";
//        if (this.get_SelectionMode() == 1)
//            selection = "single";
//        else if (this.get_SelectionMode() == 2)
//            selection = "singlecell";
//        else if (this.get_SelectionMode() == 3)
//            selection = "cellblock";
//        else if (this.get_SelectionMode() == 4)
//            selection = "cellrange";

        var config = {
            caption: this.get_Caption(),
            //selectionMode: selection,
            draggableColumns: this.get_DraggableColumns()
        };
        
        if (this.get_Width())
            config.width = this.get_Width();

        if (this.get_Height())
            config.height = this.get_Height();

        var initialRequest = "";
        if (this.get_DefaultSortColumnKey()) {
            config.sortedBy =
                {
                    key: this.get_DefaultSortColumnKey(),
                    dir: this.get_DefaultSortOrder() == 1 ? YAHOO.widget.DataTable.CLASS_DESC : YAHOO.widget.DataTable.CLASS_ASC
                };

            initialRequest = String.format("sort={0}&dir={1}&startIndex=0", this.get_DefaultSortColumnKey(), this.get_DefaultSortOrder() == 1 ? "desc" : "asc");
        }

        if (this.get_ResultsPerPage())
            initialRequest += "&results=" + this.get_ResultsPerPage();

        //handle paging...
        if(this.get_HidePaginator())
        {}
        else if (this.get_PaginatorInstance() && this.get_ResultsPerPage() > 0) // no paginator defined: use the default
        {
            $find(this.get_PaginatorInstance()).initializeYUIControl(); //intialize paginator
            config.paginator = $find(this.get_PaginatorInstance()).get_YUIControl();
        }

        if (this.get_Source().URL) { // lazy
            config.dynamicData = true;
            config.initialRequest = initialRequest; // Initial request for first page of data
        }

        if (this.get_OnRowFormat()) {
            config.formatRow = window[this.get_OnRowFormat()];
        }

        return config;
    },

    _parseColumns: function() {
        var yuiCols = [];

        for (var idx = 0; idx < this.get_Columns().length; idx++) {
            var item = this.get_Columns()[idx];
            var col =
                {
                    key: item.Key,
                    label: item.Text,
                    hidden: !item.Visible,
                    resizeable: !!item.Resizeable,
                    selected: !!item.Selected,
                    sortable: !!item.Sortable
                };
            if (item.Width && item.Width > 0)
                col.width = item.Width;

            if (item.MinWidth && item.MinWidth > 0)
                col.minWidth = item.MinWidth;

            if (item.MaxAutoWidth && item.MaxAutoWidth > 0)
                col.maxAutoWidth = item.MaxAutoWidth;

            var itemFormat = item.TemplateFormat;

            if (item.Format == 1) { //date
                col.formatter = "date";
                col.dateOption = { format: itemFormat.Format };
            }
            else if (item.Format == 2) { //number
                col.formatter = "currency";
                col.currencyOptions = {
                    decimalPlaces: itemFormat.DecimalPlaces,
                    decimalSeparator: itemFormat.DecimalSeparator,
                    thousandsSeparator: itemFormat.ThousandsSeparator
                };
            }
            else if (item.Format == 3) { // currency
                col.formatter = "currency";
                col.currencyOptions = {
                    prefix: itemFormat.Prefix,
                    decimalPlaces: itemFormat.DecimalPlaces,
                    decimalSeparator: itemFormat.DecimalSeparator,
                    thousandsSeparator: itemFormat.ThousandsSeparator
                };
            }
            else if (item.Format == 4) // custom formatter
            {
                this._buildCustomFormatter(col, itemFormat.Template);
            }
            else if (item.Format == 5) // javascript function
            {
                //YAHOO.widget.DataTable.Formatter[itemFormat.ClientFunctionName] = window[itemFormat.ClientFunctionName];
                col.formatter = window[itemFormat.ClientFunctionName];
            }

            yuiCols.push(col);
        }

        return yuiCols;
    },

    _buildCustomFormatter: function(column, template) {
        var tmpl = template;
        column.formatter = function(elCell, oRecord, oColumn, oData) {
            elCell.innerHTML = String.format(tmpl, oData);
        };
    },

    // ritl.de
    getSelectedRows: function() {
    var elRow, selectedRows;
    var oRecord = new YAHOO.widget.RecordSet();
        var Records = [];
        var grid = this.get_Grid();
        selectedRows = grid.getSelectedRows();
        for (var i = 0; i < selectedRows.length; i++) {
            elRow = grid.getTrEl(selectedRows[i]);
            oRecord = grid.getRecord(elRow);

            Records.push(oRecord._oData);
        YAHOO.log("Record " + oRecord.getData("Laufnummer"), "info", this.toString());
        }
        return Records;
    },
    // ritl.de
    get_Grid: function() {
        return this._yuiControl;
    },
    
    get_EnableRowSelection: function() {
        return this._enableRowSelection;
    },
    set_EnableRowSelection: function(enableRowSelection) {
        this._enableRowSelection = enableRowSelection;
    },
    
    get_EnableRowHover: function() {
        return this._enableRowHover;
    },
    set_EnableRowHover: function(enableRowHover) {
        this._enableRowHover = enableRowHover;
    },
    
    get_HidePaginator: function() {
        return this._hidePaginator;
    },
    set_HidePaginator: function(hidePaginator) {
        this._hidePaginator = hidePaginator;
    },
    
    get_PaginatorInstance: function() {
        return this._paginatorInstance;
    },
    set_PaginatorInstance: function(paginatorInstance) {
        this._paginatorInstance = paginatorInstance;
    },
        
    get_ResultsPerPage: function() {
        return this._resultsPerPage;
    },
    set_ResultsPerPage: function(resultsPerPage) {
        this._resultsPerPage = resultsPerPage;
    },

    get_DefaultSortOrder: function() {
        return this._defaultSortOrder;
    },
    set_DefaultSortOrder: function(defaultSortOrder) {
        this._defaultSortOrder = defaultSortOrder;
    },

    get_DefaultSortColumnKey: function() {
        return this._defaultSortColumnKey;
    },
    set_DefaultSortColumnKey: function(defaultSortColumnKey) {
        this._defaultSortColumnKey = defaultSortColumnKey;
    },

    get_Width: function() {
        return this._width;
    },
    set_Width: function(width) {
        this._width = width;
    },

    get_Height: function() {
        return this._height;
    },
    set_Height: function(height) {
        this._height = height;
    },

//    get_SelectionMode: function() {
//        return this._selectionMode;
//    },
//    set_SelectionMode: function(selectionMode) {
//        this._selectionMode = selectionMode;
//    },

    get_DraggableColumns: function() {
        return this._draggableColumns;
    },
    set_DraggableColumns: function(draggableColumns) {
        this._draggableColumns = draggableColumns;
    },

    get_Caption: function() {
        return this._caption;
    },
    set_Caption: function(caption) {
        this._caption = caption;
    },

    get_Container: function() {
        return this._container;
    },
    set_Container: function(container) {
        this._container = container;
    },

    get_Columns: function() {
        return this._columns;
    },
    set_Columns: function(columns) {
        this._columns = columns;
    },

    get_OnRowFormat: function() {
        return this._onRowFormat;
    },
    set_OnRowFormat: function(onRowFormat) {
        this._onRowFormat = onRowFormat;
    }
}

YUIAspNet.DataTable.registerClass('YUIAspNet.DataTable', YUIAspNet.BaseControl);
